<template>
	<div class="table-box">
		<ProTable ref="roleTable" title="角色列表" row-key="roleId" :columns="columns" :request-api="getRoleListApi">
			<!-- 表格 header 按钮 -->
			<template #tableHeader>
				<el-button type="primary" :icon="CirclePlus" @click="openRoleDialog('新增', {})">新增角色</el-button>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="View" @click="openRoleDialog('查看', scope.row)">查看</el-button>
				<el-button type="primary" link :icon="EditPen" @click="openRoleDialog('编辑', scope.row)">编辑</el-button>
				<el-button type="danger" link :icon="Delete" @click="deleteRole(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<el-dialog v-model="roleVisible" :title="roleTitle" :destroy-on-close="true" width="30%" draggable>
			<el-form label-width="100px" ref="roleFormRef" :model="roleFormModel" :disabled="roleTitle == '查看'">
				<el-form-item
					label="角色名称"
					prop="roleName"
					:rules="[
						{
							required: true,
							message: '请填写角色名称',
							trigger: 'blur'
						}
					]"
				>
					<el-input v-model="roleFormModel.roleName" placeholder="请填写角色名称" clearable></el-input>
				</el-form-item>
				<el-form-item
					label="权限字符"
					prop="roleKey"
					:rules="[
						{
							required: true,
							message: '请填写权限字符',
							trigger: 'blur'
						}
					]"
				>
					<el-input v-model="roleFormModel.roleKey" placeholder="请填写权限字符" clearable></el-input>
				</el-form-item>
				<el-form-item label="菜单权限">
					<div style="width: 100%">
						<TreeFilter
							ref="menuRef"
							style="width: 100%"
							label="menuName"
							id="menuId"
							children="children"
							multiple
							:defaultValue="defaultMenuValue"
							:default-expand-all="false"
							:expand-on-click-node="false"
							:request-api="getMenuListApi"
							@change="changeMenuTreeFilter"
						/>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<template v-if="roleTitle != '查看'">
						<el-button @click="roleVisible = false">取消</el-button>
						<el-button type="primary" @click="handleSubmit">确认</el-button>
					</template>
					<template v-else>
						<el-button @click="roleVisible = false">关闭</el-button>
					</template>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="tsx" setup name="roleManage">
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { getRoleListApi, addRoleApi, deleteRoleApi, editRoleApi } from "@/api/modules/test/role";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Setting } from "@element-plus/icons-vue";
import { nextTick, ref } from "vue";
import { FormInstance, ElMessage } from "element-plus";
import { getMenuListApi } from "@/api/modules/test/menu";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { useHandleData } from "@/hooks/useHandleData";

// 表单配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 150 },
	{
		prop: "roleName",
		label: "角色名称",
		align: "center",
		search: {
			el: "input"
		}
	},
	{ prop: "roleKey", label: "权限字符" },
	{ prop: "operation", label: "操作", width: 350, fixed: "right" }
];

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const roleTable = ref();

const roleVisible = ref(false);
const roleTitle = ref<string>("");

const roleFormRef = ref<FormInstance>();
const roleFormModel = ref({
	roleId: undefined,
	roleName: undefined, // 角色名称
	roleKey: undefined,
	menuId: '' // 菜单集合
});

const menuRef = ref();
// 弹窗菜单树默认选项
let defaultMenuValue = ref<any>([]);

// 新增/修改 弹窗
const openRoleDialog = async (title: string, row: any = {}) => {
	roleVisible.value = true;
	roleTitle.value = title;
	roleFormModel.value = row;

	if (title === '新增') {
		defaultMenuValue.value = [];
	} else {
		defaultMenuValue.value = row.menuId.split(",");
		// row.menus.forEach((item: any) => {
		// 	// defaultMenuValue.value.push(item.menuId);
		// 	roleFormModel.value.menuId = defaultMenuValue.join(",");
		// })
	}
};

const changeMenuTreeFilter = (val: string[]) => {
	roleFormModel.value.menuId = val.join(",");
};

// 提交数据
const handleSubmit = () => {
	roleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			// 新增角色
			// if (roleTitle.value === '新增') {
			// 	const data = await addRoleApi(roleFormModel.value);
			// 	ElMessage.success({ message: `${data.message}成功！` });
			// } else {
			// 	const data = await editRoleApi(roleFormModel.value);
			// 	ElMessage.success({ message: `${data.message}成功！` });
			// }

			const data = await addRoleApi(roleFormModel.value);
			ElMessage.success({ message: `${data.message}成功！` });
			
			roleTable.value.getTableList!();
			roleVisible.value = false;
		} catch (err) {
			console.log(err);
		}
	});
};

// 删除角色
const deleteRole = async (val: any) => {
	await useHandleData(deleteRoleApi, {roleId: val.roleId}, "删除角色");
	roleTable.value.getTableList();
}
</script>